package com.ldl.exam.controllerBack;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.ldl.exam.constant.Constants;
import com.ldl.exam.entity.*;
import com.ldl.exam.exception.ExamException;
import com.ldl.exam.service.ExamPaperService;
import com.ldl.exam.util.AjaxResult;
import com.ldl.exam.util.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * @author liudaolin
 * @version 1.0
 * @date 2022/10/09 15:54:11
 */
@RestController
@RequestMapping("/back/paper")
public class ExamPaperManageController {
    @Autowired
    private ExamPaperService examPaperService;

    // 根据 stuId 分页查询 学生的所有考试的基本信息
    //@RequestMapping("/findExams")
    public AjaxResult findExamsByStuIdAndPage(Integer stuId, Integer pageNum, Integer pageSize, HttpSession session) {
        if(null == pageSize) {
            pageSize = Constants.DEFAULT_PAGE_SIZE;
        }
        if(null == pageNum) {
            pageNum = Constants.DEFAULT_PAGE_NUM;
        }
        // TODO: 权限才能执行

        PageInfo<StuExamPaper> pageInfo = examPaperService.findExamsByStuIdAndPage(stuId, pageNum, pageSize);
        return AjaxResult.isOk("查询成功", pageInfo);
    }

    // 预览某个学生的某个试卷内容 已测
    @RequestMapping("/previewExam")
    public AjaxResult previewExamByStuIdAndExamId(Integer stuId, Integer examPaperId, HttpSession session) {
        // TODO: 权限才能执行
        StuExamPaper stuExamPaper = examPaperService.previewExamByStuIdAndExamId(stuId, examPaperId);
        return AjaxResult.isOk("查询成功", stuExamPaper);
    }

    // 创建试卷
    @RequestMapping("/createExam")
    public AjaxResult createExam(String examName) {
        // TODO: 1.有权限才能执行
//        String language = "JavaSE";
//        int choiceCount = 25;// 25* 2 = 50
//        int shortCount = 4;// 4* 5 = 20
//        int programmingCount = 2;// 2* 15 = 30
//        String code = examPaperService.createJavaExam(examName, language, choiceCount, shortCount, programmingCount);
        String code = examPaperService.createExamPaper(examName);
        return AjaxResult.isOk("试卷成功生成", code);
    }

    // 修改状态, 学生才可以开始考试 已测
    @RequestMapping("/startExam")
    public AjaxResult startExam(Integer examPaperId) {
        if(null == examPaperId) {
            throw new ExamException("请求参数缺失!");
        }
        // TODO: 1.有权限才能执行
        examPaperService.startExam(examPaperId);
        return AjaxResult.isOk("可以开始考试了");
    }

    // 结束考试 已测
    @RequestMapping("/finishExam")
    public AjaxResult finishExam(Integer examPaperId) {
        if(null == examPaperId) {
            throw new ExamException("请求参数缺失!");
        }
        // TODO: 1.有权限才能执行
        examPaperService.finishExam(examPaperId);
        return AjaxResult.isOk("结束考试, 选择题已批改完成");
    }

    // 批改试卷 已测
    @RequestMapping("/updateStuExamScore")
    public AjaxResult updateStuExamAnswerScore(Integer examPaperId, Integer stuId, Integer totalScore, String content) {
        // TODO: 1.有权限才能执行
        // 已统计过排名的考试, 不能修改得分
        // content 中 StuExamAnswer 需要有 id, score, questionId 的值
        ObjectMapper mapper = new ObjectMapper();
        TypeReference<List<StuExamAnswer>> typeReference = new TypeReference<List<StuExamAnswer>>() {};
        try {
            List<StuExamAnswer> answers = mapper.readValue(content, typeReference);
            examPaperService.updateStuExamAnswerScore(examPaperId, stuId, answers, totalScore);
            return AjaxResult.isOk("分数提交成功");
        } catch (JsonProcessingException e) {
            return AjaxResult.isFail("分数提交失败, 原因: "+ e.getMessage() +" ,请联系管理员.");
        }
    }

    // 试卷分页查询 已测
    @RequestMapping("/findExamsByPage")
    public AjaxResult findExamsByPage(Integer pageNum, Integer pageSize) {
        if(null == pageSize) {
            pageSize = Constants.DEFAULT_PAGE_SIZE;
        }
        if(null == pageNum) {
            pageNum = Constants.DEFAULT_PAGE_NUM;
        }
        // TODO: 1.有权限才能执行
        PageInfo<ExamPaper> pageInfo = examPaperService.findExamsByPage(pageNum, pageSize);
        return AjaxResult.isOk("查询成功", pageInfo);
    }

    // 某次考试中所有学生的 答卷 分页查询 已测
    @RequestMapping("/findStuExamsByExamPaperIdAndPage")
    public AjaxResult findStuExamsByExamPaperIdAndPage(Integer examPaperId, Integer pageNum, Integer pageSize) {
        if(null == examPaperId) {
            return AjaxResult.isFail("缺失必要参数");
        }
        if(null == pageSize) {
            pageSize = Constants.DEFAULT_PAGE_SIZE;
        }
        if(null == pageNum) {
            pageNum = Constants.DEFAULT_PAGE_NUM;
        }
        // TODO: 1.有权限才能执行
        PageInfo<StuExamPaper> pageInfo = examPaperService.findStuExamsByExamPaperIdAndPage(examPaperId, pageNum, pageSize);
        return AjaxResult.isOk("查询成功", pageInfo);
    }

    // 对某次考试的成绩进行排名, 并修改试卷的状态为 已排名, 已测
    @RequestMapping("/examRanking")
    public AjaxResult doExamRanking(Integer examPaperId){
        if(null == examPaperId) {
            return AjaxResult.isFail("缺失必要参数");
        }
        examPaperService.examRanking(examPaperId);
        return AjaxResult.isOk("完成排名");
    }

    // 删除某个试卷(部分真删), t_exam_paper, t_exam_paper_detail
    @RequestMapping("/removeExam")
    public AjaxResult removeExam(Integer examPaperId){
        return AjaxResult.isOk("");
    }


    @RequestMapping("/findExamQt")
    public AjaxResult findExamQt(Integer examPaperId){
        List<QuestionWithBLOBs> list = examPaperService.findExamQuestionsById(examPaperId);
        return AjaxResult.isOk("查询成功", list);
    }

    @RequestMapping("/findQuestionsByPage")
    public AjaxResult findQuestionsByPage(Integer pageNum, Integer pageSize, Integer typeId, String language){
        if(null == pageSize) {
            pageSize = Constants.DEFAULT_PAGE_SIZE;
        }
        if(null == pageNum) {
            pageNum = Constants.DEFAULT_PAGE_NUM;
        }
        PageInfo<QuestionWithBLOBs> pageInfo = examPaperService.findQuestionsByPage(pageNum, pageSize, typeId, language);
        return AjaxResult.isOk("查询成功", pageInfo);
    }

    // addQtToExam 把选中的题目加入试卷
    @RequestMapping("/addQtToExam")
    public AjaxResult addQtToExam(Integer examPaperId, String questionIds){
        if(null == examPaperId || CommonUtil.isEmpty(questionIds)) {
            return AjaxResult.isFail("缺失必要参数");
        }
        String[] arr = questionIds.split(",");
        // 存储 加入试卷的 题目id
        List<Integer> list = new ArrayList<>();
        for (String key : arr) {
            try {
                list.add(Integer.parseInt(key));
            } catch (NumberFormatException e) {
                return AjaxResult.isFail("参数格式错误");
            }
        }

        examPaperService.addQuestionToExam(examPaperId, list);
        return AjaxResult.isOk("添加成功");
    }

    // removeQtFromExam 把选中的题目从试卷中移除
    @RequestMapping("/removeQtFromExam")
    public AjaxResult removeQtFromExam(Integer examPaperId, String questionIds){
        if(null == examPaperId || CommonUtil.isEmpty(questionIds)) {
            return AjaxResult.isFail("缺失必要参数");
        }
        String[] arr = questionIds.split(",");
        // 存储 从试卷中 删除的 题目id
        List<Integer> list = new ArrayList<>();
        for (String key : arr) {
            try {
                list.add(Integer.parseInt(key));
            } catch (NumberFormatException e) {
                return AjaxResult.isFail("参数格式错误");
            }
        }

        examPaperService.removeQtFromExam(examPaperId, list);
        return AjaxResult.isOk("删除成功");
    }

}
